﻿using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text;

public partial class UserDefinedFunctions
{
    [SqlFunction]
    public static SqlString RC4Eencrypt([SqlFacet(IsNullable = true)] SqlString sKey, [SqlFacet(IsNullable = true)] SqlString sData)
    {
        SqlString sOutPut = null;
        try
        {
            if ((!sKey.IsNull && !sData.IsNull) && (sKey.ToString() != "" && sData.ToString() != ""))
            {
                SQLCrypt.RC4.RC4Engine rc4 = new SQLCrypt.RC4.RC4Engine();

                rc4.EncryptionKey = sKey.ToString();
                rc4.InClearText = sData.ToString();
                rc4.Encrypt();

                byte[] bTemp = Encoding.Unicode.GetBytes(rc4.CryptedText);
                sOutPut = Convert.ToBase64String(bTemp);
            }
            return (sOutPut);
        }
        catch (Exception)
        {
            throw new Exception("Failed to Encrypt");
        }
    }


    [SqlFunction]
    public static SqlString RC4Decrypt([SqlFacet(IsNullable = true)] SqlString sKey, [SqlFacet(IsNullable = true)] SqlString sData)
    {
        SqlString sOutPut = null;
        try
        {
            if ((!sKey.IsNull && !sData.IsNull) && (sKey.ToString() != "" && sData.ToString() != ""))
            {
                SQLCrypt.RC4.RC4Engine rc4 = new SQLCrypt.RC4.RC4Engine();
                rc4.EncryptionKey = sKey.ToString();

                Encoding enc_default = Encoding.Unicode;
                byte[] bTemp = Convert.FromBase64String(sData.ToString());
                char[] cTemp = new char[enc_default.GetCharCount(bTemp, 0, bTemp.Length)];
                enc_default.GetChars(bTemp, 0, bTemp.Length, cTemp, 0);

                rc4.CryptedText = new string(cTemp);
                rc4.Decrypt();

                sOutPut = rc4.CryptedText;
            }
            return (sOutPut);
        }
        catch (Exception)
        {
            throw new Exception("Failed to Decrypt");
        }
    }
};

